package mp;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;

public class WordCountApp {

	static class TokenizerMapper extends Mapper<Object,Text,Text,IntWritable>{
		
		private final static IntWritable one = new IntWritable(1);
		private Text word = new Text();
		/**
		 * 划分一行文本,读一单词写出一个<单词,1>
		 */
		@Override
		protected void map(Object k1, Text v1, Context context)
				throws IOException, InterruptedException {
			System.out.println("k1==" + k1.toString());  //查看k1的值
			System.out.println("v1==" + v1.toString());  //查看v1的值
			StringTokenizer itr = new StringTokenizer(v1.toString());
			while(itr.hasMoreTokens()){
				context.write(word, one);	//组成<单词,1>
			}
		}
	}
	
	static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable>{

		private IntWritable result = new IntWritable();
		@Override
		protected void reduce(Text k2, Iterable<IntWritable> v2s,
				Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
			
			int sums = 0;
			//遍历map传来的集合
			for(IntWritable val : v2s){
				//求和
				sums += val.get();	//相当于<Hello,1><Hello,1>将两个1累加
			}
			result.set(sums);
			context.write(k2, result);	//组成<k2这个单词,这个单词出现的次数>
		}
	}
	
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		Configuration conf = new Configuration();
		Job job = new Job(conf, "WordCountApp");
		job.setInputFormatClass(TextInputFormat.class);	//对输入文件格式化
		TextInputFormat.setInputPaths(job, args[0]);	//待处理文件位置
		job.setJarByClass(WordCountApp.class);	//主类名
		job.setMapperClass(TokenizerMapper.class);	//指定Mapper类
		job.setCombinerClass(IntSumReducer.class);	//指定Combiner函数
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		job.setPartitionerClass(HashPartitioner.class);
		job.setReducerClass(IntSumReducer.class);
		job.setNumReduceTasks(Integer.parseInt(args[2]));
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.setOutputFormatClass(TextOutputFormat.class);//对输出格式类
		TextOutputFormat.setOutputPath(job, new Path(args[1]));
		System.exit(job.waitForCompletion(true)?0:1);
		
	}
}
